<?php

namespace app\common\traits;

use app\common\libs\OssLib;
use think\Exception;
use think\facade\Filesystem;

/**
 *  上传文件
 */
trait UploadsOssTrait
{

    /**
     * 上传文件到oss中
     * @param string $dirName
     * @return array
     * @throws Exception
     */
    public function uploadFile(string $dirName = 'images'): array
    {
        $files = request()->file();
        if (empty($files) || (is_array($files) && count($files) <= 0)) {
            throw new Exception('您未上传任何图片', API_ERROR);
        }
        // 获取驱动信息
        $filesystem = config('filesystem');
        $drive_name = $filesystem['default'];
        $drive_info = $filesystem['disks'][$drive_name];
        $prefix = $drive_info['url'] ?? '';
        $root_dir = $drive_info['dir'] ?? '';
        $file_list = [];
        foreach ($files as $file) {
            $save_name = Filesystem::putFile($root_dir . '/' . $dirName, $file);
            $file_list[] = $prefix . '/' . $save_name;
        }
        saveUploadLog($file_list);
        return $file_list;
    }

    /**
     * 删除OSS中的文件
     * @param string $url
     * @return mixed
     * @throws Exception
     */
    public function deleteFile(string $url)
    {
        $filesystem = config('filesystem');
        $drive_name = $filesystem['default'];
        // 从OSS中删除
        if ($drive_name === 'aliyun') {
            OssLib::getInstance($filesystem['disks'][$drive_name])->deleteFile($url);
        } else {
            $url = '.' . $url;
            if (file_exists($url)) {
                @@unlink($url);
            }


        }
        return deleteUploadLog($url);
    }
}
